package com.wangsanfei.util;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class SMSUtils {
	
	public static Logger logger=Logger.getLogger(SMSUtils.class);
	
	/**
	 * 服务http地址
	 */
	private static String BASE_URI = "http://yunpian.com";
	/**
	 * 服务版本号
	 */
	private static String VERSION = "v1";
	/**
	 * 编码格式
	 */
	private static String ENCODING = "UTF-8";
	/**
	 * 查账户信息的http地址
	 */
	@SuppressWarnings("unused")
	private static String URI_GET_USER_INFO = BASE_URI + "/" + VERSION + "/user/get.json";
	/**
	 * 通用发送接口的http地址
	 */
	private static String URI_SEND_SMS = BASE_URI + "/" + VERSION + "/sms/send.json";
	/**
	 * 模板发送接口的http地址
	 */
	@SuppressWarnings("unused")
	private static String URI_TPL_SEND_SMS = BASE_URI + "/" + VERSION + "/sms/tpl_send.json";

	/**
	 * APIKEY
	 */
	private static String  APIKEY= "06a316c1ebd109d66621f085184c5f2a111111";
	
	
	/**
	 * 取账户信息
	 * @return json格式字符串
	 * @throws IOException 
	 */
	public static String getUserInfo(String apikey) throws IOException{
		return null;
	}
	
	
	/**
	 * 发短信
	 * @param apikey apikey
	 * @param text　短信内容　
	 * @param mobile　接受的手机号
	 * @return json格式字符串
	 * @throws IOException 
	 */
	private static String sendSmsOnlySend(String text, String mobile){
		CloseableHttpResponse response=null;
		String json=null;
		try {
			
			CloseableHttpClient  httpclient = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(URI_SEND_SMS);
			List <NameValuePair> nvps = new ArrayList <NameValuePair>();
			nvps.add(new BasicNameValuePair("apikey", APIKEY));
			nvps.add(new BasicNameValuePair("text", text));
			nvps.add(new BasicNameValuePair("mobile", mobile));
			httpPost.setEntity(new UrlEncodedFormEntity(nvps,ENCODING));
			
			response = httpclient.execute(httpPost);
			
		    HttpEntity entity = response.getEntity();
		    json=EntityUtils.toString(entity);
		} catch(Exception e){
			e.printStackTrace();
		}finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return json;
	}
	
	
	@SuppressWarnings("rawtypes")
	private static void sendSmsOnlySave(String json,Record record,boolean add){
		try {
			Map map=(Map)JSON.parse(json);
			Integer code=(Integer)map.get("code");
			if(code==0){
				//发送成功
				record.set("status", "1");
			}else if(code>0){
				//调用API时发生错误，需要开发者进行相应的处理。
				logger.error("API调用错误，请发送者处理！code:"+code);
			}else if(code>-50&&code<=-1){
				//权限验证失败，需要开发者进行相应的处理。
				logger.error("权限验证失败，需要开发者进行相应的处理！code:"+code);
			}else if(code<-50){
				logger.warn("系统内部错误，请联系技术支持，调查问题原因并获得解决方案。！code:"+code);
			}
			
			try {
				if(add){
					Db.save("t_sms", record);
				}else{
					Db.update("t_sms", record);
				}
			} catch (Exception e) {
				logger.error(e.toString());
			}
			
		} catch (Exception e) {
			logger.error(e.toString());
		}
	}
	
	/**
	 * 
	 * @param text
	 * @param mobile
	 * @param userId
	 * @throws IOException
	 */
	public static void sendSms(String text, String mobile,String userId){
		String json=sendSmsOnlySend(text, mobile);
		Record record=new Record().set("id", UUIDUtils.getUUID())
					.set("cellphone", mobile)
					.set("note", text)
					.set("status", "0")
					.set("sendCount", 1)
					.set("sendTime", new Date())
					.set("userId", userId);
		sendSmsOnlySave(json,record,true);
	}
	
	public static void sendFailSms(){
		List<Record> records=Db.find("select * from t_sms t where t.status='0' and sendCount<5");
		for (Record record : records) {
			String json=sendSmsOnlySend(record.getStr("note"), record.getStr("cellphone"));
			int count=record.getInt("sendCount")+1;
			if(count==5){
				record.set("status", "2");
			}
			record.set("sendCount", count);
			sendSmsOnlySave(json,record,false);
		}
	}
	
	public static void main(String[] args) throws IOException {
		String text = "【云片网】您的验证码是7777";
		String mobile = "15560050700";
		SMSUtils.sendSms(text, mobile,"1111");
	}
}
